package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    private Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    private String prefix;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    ApAuthorMapper apAuthorMapper;

    /**
     * 根据文章id生成文章静态页面
     * @param articleId
     */
    @Override
    @Async
    public void generateArticlePage(Long articleId) {
        // 准备数据模型, authorApuserId         ApArticle apArticle = apArticleMapper.selectById(articleId);
        // 文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent == null || StringUtils.isBlank(apArticleContent.getContent())) {
            log.error("文章内容为空生成静态页失败 articleid:{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文章内容为空生成静态页失败");
        }
        // 文章
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.error("文章为空生成静态页失败 articleid:{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文章为空生成静态页失败");
        }
        // 作者id
        ApAuthor apAuthor = apAuthorMapper.selectById(apArticle.getAuthorId());
        if (apAuthor == null) {
            log.error("作者信息为空生成静态页失败 articleid:{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"作者信息为空生成静态页失败");
        }
        // article.ftl 取值,取得是 Map集合中的值
        Map params = new HashMap();
        params.put("authorApUserId", apAuthor.getUserId());
        params.put("article", apArticle);
        List<Map> list = JSONArray.parseArray(apArticleContent.getContent(), Map.class);
        params.put("content",list);

        //   获取 freemarker的模板
        try {
            Template template = configuration.getTemplate("article.ftl");
            //  基于模板+数据模型 将替换后的内容输出到流中
            StringWriter writer = new StringWriter();
            template.process(params,writer);
            //  封装输入流 静态页面存入 minio
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            // 全路径
            String path = fileStorageService.store("article", articleId + ".html", "text/html", inputStream);
            log.info("页面静态完成-->页面路径:" + path);
            // 修改 ap_article表，保存static_url字段
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("服务器出现异常,生成静态页失败, articleId:{}", articleId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "服务器出现异常, 生成静态页失败");
        }

    }
}